<template>
  <!-- 基础信息 -->
  <vab-card>
    <template #header>
      <span class="leve2_title">基础信息</span>
    </template>
    <template #default>
      <el-form
        :ref="(el) => (baseFormRef = el)"
        :model="baseForm"
        label-width="110px"
        class="form_search"
      >
        <el-row :gutter="24">
          <el-col v-for="(item, i) in _CreateBaseForm" 
            :key="i" v-bind="colLay"
          >
            <!-- 默认项 -->
            <el-form-item
              v-if="item.type == 'select'"
              :label="item.label"
              :prop="item.prop"
              :rules="[
                { required: true, message: `${item.label}不能为空！`, trigger: 'blur' },
              ]"
            > 
              <VabSelectForm 
                clearable
                filterable
                :options="selectOptions(item.prop)"
                class="width_100" 
                placeholder="请选择"
                v-model="baseForm[item.prop]" 
                :multiple="item.multiple"
                :disabled="item.disabled"
                @change="handleChange(item.prop, baseForm[item.prop])"
              />
            </el-form-item>
          </el-col>
          <el-col v-bind="colLay">
            <el-form-item
              label="信用对象范围"
              prop="object_type"
              :rules="[
                { required: true, message: `信用对象范围不能为空！`, trigger: 'blur' },
              ]"
            >
            <VabSelectForm 
              :ref="(el: any) => vabSelectFormRef = el"
              clearable
              filterable
              :options="selectOptions('object_type')"
              class="width_100" 
              placeholder="请选择"
              v-model="baseForm.object_type" 
              @change="handleObjectType(baseForm.object_type)"
            />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="16" :xl="16">
            <el-form-item
              label="备注"
              prop="note"
            >
              <VabInputForm v-model.trim="baseForm.note" :type="'textarea'"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </vab-card>

  <!-- 信用对象设置 -->
  <vab-card>
    <template #header>
      <div class="flex leve2_title">
        信用对象设置 
        <span class="pour_text flex">注： <sapn class="required_text">*</sapn> 为必填项</span>
      </div>
    </template>
    <div :class="{ 'warn': isWarn }">
      <el-form 
        :ref="(el) => productFormRef = el" 
        :model="productList" 
        class="formData"
      >
        <el-table
          border
          height="430px"
          :data="productList"
        >
          <el-table-column label="序号" align="center" width="60">
            <template #default="props">
              {{ props.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="customer_name" align="center" width="300">
            <template #header>
              <span class="required_text">*</span>
              <span>信用对象</span>
            </template>
            <template #default="props">
              <el-form-item prop="customer_name" >
                <CustomLazySelect
                  :use_org_id="baseForm.org_id"
                  :is_group="baseForm.object_type"
                  v-model="props.row.customer_name" 
                  @LazyChange="(row: any) => {
                    productQuerySearch(row, props.$index)
                  }"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="customer_number" align="center" width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>客户编码</span>
            </template>
            <template #default="props">
              <span
                class="ellipsis"
                v-text="FieldFormat(props.row.customer_number)"
              ></span>
            </template>
          </el-table-column>
          <el-table-column prop="currency_id" align="center" width="140">
            <template #header>
              <span class="required_text">*</span>
              <span>币别</span>
            </template>
            <template #default="props">
              <el-form-item  prop="currency_id"> 
                <VabSelectForm 
                  clearable
                  filterable
                  :options="selectOptions('currency_id')"
                  class="width_100" 
                  placeholder="请选择"
                  v-model.trim="props.row.currency_id"
                  @change="handleRetrunName('currency', props.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="credit_amount" align="center" width="160">
            <template #header>
              <span class="required_text">*</span>
              <span>信用额度</span>
            </template>
            <template #default="props">
              <el-form-item prop="credit_amount">
                <el-input-number
                  :min="0"
                  :precision="2"
                  :controls="false"
                  class="width_100"
                  placeholder="请输入"
                  v-model.trim="props.row.credit_amount"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="credit_status" align="center" width="140">
            <template #header>
              <span class="required_text">*</span>
              <span>信用状态</span>
            </template>
            <template #default="props">
              <el-form-item  prop="credit_status"> 
                <VabSelectForm 
                  clearable
                  filterable
                  :options="selectOptions('credit_status')"
                  class="width_100" 
                  placeholder="请选择"
                  v-model.trim="props.row.credit_status"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="check_role_id" align="center" min-width="200">
            <template #header>
              <span class="required_text">*</span>
              <span>检查规则</span>
            </template>
            <template #default="props">
              <el-form-item  prop="check_role_id"> 
                <VabSelectForm 
                  clearable
                  filterable
                  :options="selectOptions('check_role_id')"
                  class="width_100" 
                  placeholder="请选择"
                  v-model.trim="props.row.check_role_id"
                  @change="handleRetrunName('check_role', props.$index)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="70">
            <template #default="props">
              <vab-icon
                icon="add-circle-line"
                class="icon_color"
                @click="handleAdd(props.$index)"
              />
              <vab-icon
                v-if="productList.length > 1"
                icon="delete-bin-5-line"
                @click="handleRemove(props.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </vab-card>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ProductsInformation',
})
/**
 * @props
 */
const props = defineProps({
  isWarn: {
    type: Boolean,
    default: false,
  },
  fromPage: {
    type: String,
    default: ''
  }
})
/**
 * @import
 */
import { ref } from 'vue'
import { FieldFormat } from '/@/utils/utils'
import CustomLazySelect from './CustomLazySelect.vue'
import { CreateBaseForm, ReturnSelectOptions } from './tools';
import { ElMessageBox } from 'element-plus';
/**
 * @var
 */
const colLay = {
  xs: 24, sm: 12, md: 12, lg: 8, xl: 8,
}

const proxy: any = getCurrentInstance()?.proxy
const baseFormRef = ref<any>(null)
const vabSelectFormRef = ref<any>()
const _CreateBaseForm = ref<any>([...CreateBaseForm])
let baseForm = ref<any>({})

const checkObjectType = ref<any>('')

const sreachScreen = ref<any>(null)

// 基础信息
const baseRow = ref({
  check_role_id: '101957',
  check_role_name: '黛优佳信用检查规则',
  credit_status: 1,
  customer_name: '',
  customer_id: '',
  customer_number: '',
  currency_id: '1',
  currency_name: '人民币'
})

/**
 * @method
 */

const productFormRef = ref()
// 基础五个数据
const productList = ref<any>([])
// 创建默认五条基本信息
if (props.fromPage == 'create') {
  for (let index = 0; index < 5; index++) {
    productList.value.push({ ...baseRow.value })
  }
}

const copyData = ref<any>([]) //拿到的复制数据

/**
 * @method
 */

// 添加
const handleAdd = (i: number) => {
  productList.value.splice(i + 1, 0, {
    check_role_id: '101957',
    check_role_name: '黛优佳信用检查规则',
    credit_status: 1,
    currency_id: '1',
    currency_name: '人民币'
  })
}
// 删除
const handleRemove = (index: number) => {
  productList.value.splice(index, 1)
}
const handleChange = (prop: string, value: any) => {
  if (prop == 'ctrl_scope') {
    if (value == '1') {
      _CreateBaseForm.value[1]['disabled'] = true
      baseForm.value.org_id = '1'
    }
    if (value == '3' || value == '') {
      _CreateBaseForm.value[1]['disabled'] = false
      baseForm.value.org_id = ''
    }
    return
  }
}
// 切换信用对象范围
const handleObjectType = (value: string) => {
  if (checkObjectType.value && checkObjectType.value != value) {
    ElMessageBox.confirm('切换信用对象范围，会清空信用对象设置，是否确认', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        // 清除焦点
        vabSelectFormRef.value.selectRef.$refs.reference.blur()
        // 赋值
        baseForm.value.object_type = value
        // 判断key
        checkObjectType.value = value
        // 清空
        for (let index = 0; index < 5; index++) {
          productList.value[index] = {
            check_role_id: '101957',
            check_role_name: '黛优佳信用检查规则',
            credit_status: 1,
            currency_id: '1',
            currency_name: '人民币'
          }
        }
      })
      .catch(() => {
        vabSelectFormRef.value.selectRef.$refs.reference.blur()
        baseForm.value.object_type = checkObjectType.value
      })
  } else {
    checkObjectType.value = value
  }
}

// 重置数据
const resetData = (value: any) => {
  productList.value = [{}]
}
// 筛选项返回值
const selectOptions = (value: string) => {
  if (!sreachScreen.value) return
  if (!value) return
  return ReturnSelectOptions(sreachScreen.value, value)
}
//获取筛选项
const getScreen = async (res: any) => {
  sreachScreen.value = await res
}
// 客户带出基本信息
const productQuerySearch = async (row: any, i: number) => {
  if (productList.value.length > 1) {
    let voidNumber = false
    voidNumber = await productList.value.some(
      (item: any) => item.customer_number == row.number
    )
    if (voidNumber) {
      proxy.$Message('信用对象重复,请重新选择！', 'warning')
      productList.value[i] = {
        check_role_id: '101957',
        check_role_name: '黛优佳信用检查规则',
        credit_status: 1,
        currency_id: '1',
        currency_name: '人民币'
      }
      return
    }

  }
  productList.value[i].customer_number = row.number
  productList.value[i].customer_id = row.uid

}
// 返回对应名称
const handleRetrunName = (prop: string, i: number) => {
  // 数据
  const list = selectOptions(`${prop}_id`)
  // 选择id
  const value = productList.value[i][`${prop}_id`]
  // 对应对象
  const row = list.filter((item: any) => item.value == value)
  // 对应name
  productList.value[i][`${prop}_name`] = row[0].label
}
// 获取更新数据
const getUpdateData = async (res: any) => {
  baseForm.value = await {
    ...res,
    ctrl_scope: `${res.ctrl_scope}`,
    object_type: `${res.object_type}`,
    org_id: `${res.org_id}`,
    note: res.note,
  }
  checkObjectType.value = `${res.object_type}`

  copyData.value = []
  copyData.value = await res.customer_list.map((item: any) => {
    return {
      ...item,
      currency_id: `${item.currency_id}`,
      ctrl_scope: `${item.ctrl_scope}`,
      org_id: `${item.org_id}`,
      check_role_id: `${item.check_role_id}`,
    }
  }) || []
  productList.value = copyData.value


  // 执行禁用操作
  handleChange('ctrl_scope', res.ctrl_scope)
}

/**
 * @实例
 */

//抛出数据
defineExpose({
  baseFormRef,
  baseForm,
  productFormRef,
  productList,
  getScreen,
  resetData,
  getUpdateData,
})
onMounted(() => {
  // 默认禁用
  baseForm.value.ctrl_scope = '1'
  baseForm.value.org_id = '1'
})
</script>

<style lang="scss" scoped>
:deep() {
  .el-loading-spinner {
    display: none;
  }
}

.products_font1 {
  font-size: 16px;
  margin-bottom: 15px;
}

.products_div {
  width: 300px;
}

.products_div1 {
  margin-right: 20px;
  margin-left: 10px;
  display: inline-block;

  :deep() {
    .el-input__wrapper {
      border-bottom-right-radius: 0px !important;
      border-top-right-radius: 0px !important;
      border-right: 0px solid !important;
    }

    .el-button {
      border-bottom-left-radius: 0px !important;
      border-top-left-radius: 0px !important;
      border-left: 0px solid !important;
    }
  }
}

.products_font2 {
  color: rgb(245, 154, 35);
  margin-left: 20px;
}

.products_div2 {
  margin-right: 20px;
}

.products_div3 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  margin-top: 25px;
}

.formData {
  :deep() {
    .el-form-item {
      margin-bottom: 0px;
    }
  }

  .icon_color {
    color: #0967f4;
    margin-right: 4px;
  }
}

.warn {
  border: 2px dashed red;
}
</style>
